package com.only4play.practice.pay.payment.kit;

import cn.hutool.core.util.ObjUtil;
import com.only4play.codegen.support.exception.BusinessException;
import com.only4play.codegen.support.model.JsonObject;
import com.only4play.practice.common.BizCodeEnum;
import com.only4play.practice.common.enums.pay.OutPayChannelType;
import com.only4play.practice.pay.payment.kit.request.PayParamRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author mengdy
 */
@Component
@Slf4j
public class CashierSupport {


    public JsonObject<Object> payment(HttpServletRequest request, HttpServletResponse response,
                                      PayParamRequest payParam) {

        // 获取支付插件
        if (!OutPayChannelType.of(payParam.getChannelType()).isPresent()){
            throw new BusinessException(BizCodeEnum.PAY_ORDER_PAY_FAIL);
        }
        PaymentPlugin paymentPlugin = PaymentPluginFactory.getPaymentPlugin(OutPayChannelType.of(payParam.getChannelType()).get());
        if (ObjUtil.isNull(paymentPlugin)){
            throw new RuntimeException("支付插件不存在");
        }
        return paymentPlugin.unifiedOrder(request,payParam);
    }

    public String unifiedCallback(HttpServletRequest request, String channelType, String outTradeOrderNo, Map<String, String> params) {

        log.info("支付回调.....{} , {}", channelType, outTradeOrderNo);
        if (!OutPayChannelType.of(Integer.parseInt(channelType)).isPresent()){
            throw new BusinessException(BizCodeEnum.PAY_ORDER_PAY_FAIL);
        }
        PaymentPlugin paymentPlugin = PaymentPluginFactory.getPaymentPlugin(OutPayChannelType.of(Integer.parseInt(channelType)).get());
        if (ObjUtil.isNull(paymentPlugin)){
            throw new RuntimeException("支付插件不存在");
        }
        return paymentPlugin.unifiedCallback(request,params);
    }
}
